/*
 * Copyright(C) 2009, kesalin All rights reserved.
 * 
 * File name : LuoDndAssistImport.h
 * Brief     : Helper class for import dlls.
 * Version   : 1.0
 * Author    : kesalin@gmail.com
 * Date      : 2009-6-5
 */


/* */
#ifdef _DEBUG
	#define DND_ASSIST_DLL	L"LuoDnD_Debug.dll"
#else
	#define DND_ASSIST_DLL	L"LuoDnD.dll"
#endif
namespace LuoDnDAssist {

// DLLibLoader
class DLLibLoader {
	HMODULE m_hDLL;

	typedef HRESULT (STDCALL *Activate_t) (LPCWSTR token, void **obj);

	Activate_t m_func;
public:
	DLLibLoader() :
	m_hDLL(0),
	m_func(0)
	{
	}

	~DLLibLoader()
	{
		if (m_hDLL != 0) {
			FreeLibrary(m_hDLL);
		}
	}

	HRESULT Activate(LPCWSTR token, void ** obj)
	{
		if (m_hDLL == 0) {
			m_hDLL = LoadLibraryW(DND_ASSIST_DLL);

			if (m_hDLL == 0) {
				DWORD error = GetLastError();

				WCHAR errorInfo[256];
				swprintf_s(errorInfo, 256, L"ERROR: Missing '%s'\n", DND_ASSIST_DLL);
				OutputDebugStringW(errorInfo);

				return HRESULT_FROM_WIN32(error);
			}
		}

		if (m_func == 0) {
			m_func = (Activate_t) GetProcAddress(m_hDLL, "_LuoDnDAssist_Activate@8");
			if (m_func == 0) {
				DWORD error = GetLastError();
				OutputDebugStringW(L"\n ERROR: GetProcAddress - _LuoDnDAssist_Activate\n");
				return HRESULT_FROM_WIN32(error);
			}
		}

		HRESULT hRslt = m_func(token, obj);
		if (FAILED(hRslt)) {
			return hRslt;
		}

		return S_OK;
	}
};

// DLLibLoader
HRESULT STDCALL Activate_import(LPCWSTR token, void ** obj)
{
	static DLLibLoader s_Loader;

	HRESULT hRslt = s_Loader.Activate(token, obj);
	if (FAILED(hRslt)) {
		return hRslt;
	}

	return S_OK;
}
}	// namespace LuoDnDAssist
/* */
